<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加航班</el-button>

    <el-table :data="paginatedFlights" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="hbname" label="航班名称" width="150"></el-table-column>
      <el-table-column prop="flightType" label="航班类型" width="120"></el-table-column>
      <el-table-column prop="cfcity" label="出发城市" width="120"></el-table-column>
      <el-table-column prop="ddcity" label="到达城市" width="120"></el-table-column>
      <el-table-column prop="cftime" label="出发时间" width="180"></el-table-column>
      <el-table-column prop="ddtime" label="到达时间" width="180"></el-table-column>
      <el-table-column prop="jjprice" label="经济舱票价" width="100"></el-table-column>
      <el-table-column prop="jjzticket" label="经济舱余票" width="100"></el-table-column>
      <el-table-column prop="jjrticket" label="经济舱总票数" width="120"></el-table-column>
      <el-table-column prop="tdprice" label="头等舱票价" width="100"></el-table-column>
      <el-table-column prop="tdzticket" label="头等舱余票" width="100"></el-table-column>
      <el-table-column prop="tdrticket" label="头等舱总票数" width="120"></el-table-column>
      <el-table-column prop="aircraftID" label="客机ID" width="120"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteFlight(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        :total="flights.length"
        :page-size="15"
        @current-change="handlePageChange"
        style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 编辑航班对话框 -->
    <el-dialog title="编辑航班" v-model="isEditDialogVisible">
      <el-form :model="editForm">
        <el-form-item label="航班名称">
          <el-input v-model="editForm.hbname"></el-input>
        </el-form-item>
        <el-form-item label="航班类型">
          <el-input v-model="editForm.flightType"></el-input>
        </el-form-item>
        <el-form-item label="出发城市">
          <el-input v-model="editForm.cfcity"></el-input>
        </el-form-item>
        <el-form-item label="到达城市">
          <el-input v-model="editForm.ddcity"></el-input>
        </el-form-item>
        <el-form-item label="出发时间">
          <el-date-picker v-model="editForm.cftime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="到达时间">
          <el-date-picker v-model="editForm.ddtime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="经济舱票价">
          <el-input v-model="editForm.jjprice"></el-input>
        </el-form-item>
        <el-form-item label="经济舱余票">
          <el-input v-model="editForm.jjzticket"></el-input>
        </el-form-item>
        <el-form-item label="经济舱总票数">
          <el-input v-model="editForm.jjrticket"></el-input>
        </el-form-item>
        <el-form-item label="头等舱票价">
          <el-input v-model="editForm.tdprice"></el-input>
        </el-form-item>
        <el-form-item label="头等舱余票">
          <el-input v-model="editForm.tdzticket"></el-input>
        </el-form-item>
        <el-form-item label="头等舱总票数">
          <el-input v-model="editForm.tdrticket"></el-input>
        </el-form-item>
        <el-form-item label="客机ID">
          <el-input v-model="editForm.aircraftID"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateFlight">确认</el-button>
      </div>
    </el-dialog>

    <!-- 添加航班对话框 -->
    <el-dialog title="添加航班" v-model="isAddDialogVisible">
      <el-form :model="addForm">
        <el-form-item label="航班名称">
          <el-input v-model="addForm.hbname"></el-input>
        </el-form-item>
        <el-form-item label="航班类型">
          <el-input v-model="addForm.flightType"></el-input>
        </el-form-item>
        <el-form-item label="出发城市">
          <el-input v-model="addForm.cfcity"></el-input>
        </el-form-item>
        <el-form-item label="到达城市">
          <el-input v-model="addForm.ddcity"></el-input>
        </el-form-item>
        <el-form-item label="出发时间">
          <el-date-picker v-model="addForm.cftime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="到达时间">
          <el-date-picker v-model="addForm.ddtime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="经济舱票价">
          <el-input v-model="addForm.jjprice"></el-input>
        </el-form-item>
        <el-form-item label="经济舱余票">
          <el-input v-model="addForm.jjzticket"></el-input>
        </el-form-item>
        <el-form-item label="经济舱总票数">
          <el-input v-model="addForm.jjrticket"></el-input>
        </el-form-item>
        <el-form-item label="头等舱票价">
          <el-input v-model="addForm.tdprice"></el-input>
        </el-form-item>
        <el-form-item label="头等舱余票">
          <el-input v-model="addForm.tdzticket"></el-input>
        </el-form-item>
        <el-form-item label="头等舱总票数">
          <el-input v-model="addForm.tdrticket"></el-input>
        </el-form-item>
        <el-form-item label="客机ID">
          <el-input v-model="addForm.aircraftID"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addFlight">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import moment from 'moment';
import { listFlights, deleteFlight as deleteFlightAPI, updateFlight as updateFlightAPI, addFlight as addFlightAPI } from '@/api/flight.js';
import { ElMessage, ElMessageBox } from 'element-plus';

const flights = ref([]);
const paginatedFlights = ref([]);
const currentPage = ref(1);
const pageSize = ref(15);
const editForm = ref({});
const addForm = ref({});
const isEditDialogVisible = ref(false);
const isAddDialogVisible = ref(false);

const fetchFlights = async () => {
  try {
    const response = await listFlights();
    if (response.code === 1) {
      flights.value = response.data.map(flight => ({
        ...flight,
        cftime: moment(flight.cftime).format('YYYY-MM-DD HH:mm:ss'),
        ddtime: moment(flight.ddtime).format('YYYY-MM-DD HH:mm:ss')
      }));
      handlePageChange(currentPage.value);
    } else {
      throw new Error(response.msg);
    }
  } catch (error) {
    console.error('获取航班列表失败:', error);
    ElMessage.error('获取航班列表失败，请重试');
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  paginatedFlights.value = flights.value.slice(start, end);
};

const openEditDialog = (flight) => {
  editForm.value = {
    ...flight,
    cftime: moment(flight.cftime, 'YYYY-MM-DD HH:mm:ss').toDate(),
    ddtime: moment(flight.ddtime, 'YYYY-MM-DD HH:mm:ss').toDate()
  };
  isEditDialogVisible.value = true;
};

const openAddDialog = () => {
  addForm.value = {
    hbname: '',
    flightType: '',
    cfcity: '',
    ddcity: '',
    cftime: '',
    ddtime: '',
    jjprice: '',
    jjzticket: '',
    jjrticket: '',
    tdprice: '',
    tdzticket: '',
    tdrticket: '',
    aircraftID: ''
  };
  isAddDialogVisible.value = true;
};

const updateFlight = async () => {
  try {
    const updatedFlight = {
      ...editForm.value,
      cftime: moment(editForm.value.cftime).format('YYYY-MM-DD HH:mm:ss'),
      ddtime: moment(editForm.value.ddtime).format('YYYY-MM-DD HH:mm:ss')
    };
    await updateFlightAPI(updatedFlight);
    ElMessage.success('更新航班成功');
    isEditDialogVisible.value = false;
    fetchFlights();
  } catch (error) {
    console.error('更新航班失败:', error);
    ElMessage.error('更新航班失败，请重试');
  }
};

const deleteFlight = async (id) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该航班, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await deleteFlightAPI(id);
    ElMessage.success('删除航班成功');
    fetchFlights();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除航班失败:', error);
      ElMessage.error('删除航班失败，请重试');
    }
  }
};

const addFlight = async () => {
  try {
    const newFlight = {
      ...addForm.value,
      cftime: moment(addForm.value.cftime).format('YYYY-MM-DD HH:mm:ss'),
      ddtime: moment(addForm.value.ddtime).format('YYYY-MM-DD HH:mm:ss')
    };
    await addFlightAPI(newFlight);
    ElMessage.success('添加航班成功');
    isAddDialogVisible.value = false;
    fetchFlights();
  } catch (error) {
    console.error('添加航班失败:', error);
    ElMessage.error('添加航班失败，请重试');
  }
};

onMounted(fetchFlights);
</script>

<style scoped>
</style>
